package com.qingmi.farmer.ui.main;

import android.databinding.ObservableArrayList;
import android.databinding.ObservableList;
import android.text.TextUtils;
import android.view.View;

import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.qingmi.farmer.BR;
import com.qingmi.farmer.R;
import com.qingmi.farmer.data.DataSetting;
import com.qingmi.farmer.data.UserData;
import com.qingmi.farmer.data.model.Banner;
import com.qingmi.farmer.data.model.GrainDemand;
import com.qingmi.farmer.data.model.HomeData;
import com.qingmi.farmer.data.model.News;
import com.qingmi.farmer.data.repository.data.OtherDataRepository;
import com.qingmi.farmer.databinding.FragmentHomeBinding;
import com.qingmi.farmer.event.UserLoginChangeEvent;
import com.qingmi.farmer.ui.buy.GoodsDetailActivity;
import com.qingmi.farmer.ui.buy.GoodsListActivity;
import com.qingmi.farmer.ui.demand.DemandDetailActivity;
import com.qingmi.farmer.ui.demand.DemandListActivity;
import com.qingmi.farmer.ui.news.NewsListActivity;
import com.qingmi.farmer.ui.notice.NoticeActivity;
import com.qingmi.farmer.ui.webview.WebViewActivity;
import com.qingmi.farmer.viewmodel.AdViewModel;
import com.qingmi.farmer.viewmodel.GrainDemandItemViewModel;
import com.qingmi.farmer.viewmodel.GrainDemandTitleViewModel;
import com.qingmi.farmer.viewmodel.HotSellViewModel;
import com.qingmi.farmer.viewmodel.NewsItemViewModel;
import com.qingmi.farmer.viewmodel.NewsTitleViewModel;
import com.qingmi.farmer.viewmodel.NoticeListViewModel;
import com.wjjun.base.ui.base.ListFragment;
import com.wjjun.basemvpvm.data.exception.MyException;
import com.wjjun.basemvpvm.data.observer.DefaultObserver;
import com.wjjun.basemvpvm.viewmodel.BaseViewModel;
import com.wjjun.customview.views.VScrollTextView;
import com.wjjun.viewmodel.BannerItemViewModel;
import com.wjjun.viewmodel.BannerViewModel;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * 首页
 * Created by 67535 on 2018/4/28.
 */

public class HomeFragment extends ListFragment<HomeViewModel, FragmentHomeBinding> {

    //首页刷新间隔
    private static final int REFRESH_TIME_INTERVAL = 60000;

    //banner
    private BannerViewModel bannerViewModel;
    private ObservableList<BannerItemViewModel> bannerItems = new ObservableArrayList<>();

    //公告
    private NoticeListViewModel noticeItemViewModel;

    //当季热卖
    private HotSellViewModel hotSellViewModel;

    //数据
    List list = new ArrayList<>();

    @Inject
    OtherDataRepository otherDataRepository;

    @Inject
    UserData userData;

    //上次刷新时间
    private long lastRefreshTime = 0;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected HomeViewModel initViewModel() {
        return new HomeViewModel();
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void initContent() {
        otherDataRepository.bind(this);
        super.initContent();
        data.clear();

        //初始化banner
        if (bannerViewModel == null) {
            bannerViewModel = new BannerViewModel();
            bannerViewModel.setIndicatorCenter();
            bannerViewModel.setIsAutoPlay(true);
            bannerViewModel.setCircleIndicator();
        }
        bannerViewModel.setItems(bannerItems);

        data.add(bannerViewModel);

        //初始化公告
        if (noticeItemViewModel == null) {
            noticeItemViewModel = new NoticeListViewModel();
        }

        data.add(noticeItemViewModel);

        if (hotSellViewModel == null) {
            hotSellViewModel = new HotSellViewModel();
        }

        data.add(hotSellViewModel);

        commListViewModel.showLoading();

        RxBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserLoginChange(UserLoginChangeEvent event) {
        notifyDataChange();
    }

    @Override
    public void onListItemBind(ItemBinding itemBinding, int position, Object item) {
        if (item instanceof BannerViewModel) {  //banner
            itemBinding.set(BR.viewModel, R.layout.layout_banner).bindExtra(BR.listener, bannerListener);
        } else if (item instanceof NoticeListViewModel) { //公告
            itemBinding.set(BR.viewModel, R.layout.layout_notice).bindExtra(BR.presenter, viewGroupPresenter)
                    .bindExtra(BR.listener, onNoticesItemClickListener);
        } else if (item instanceof HotSellViewModel) {    //热卖
            itemBinding.set(BR.viewModel, R.layout.layout_hot_sell).bindExtra(BR.presenter, viewGroupPresenter);
        } else if (item instanceof AdViewModel) {    //广告
            itemBinding.set(BR.viewModel, R.layout.layout_ad).bindExtra(BR.presenter, viewGroupPresenter);
        } else if (item instanceof GrainDemandTitleViewModel) {   //收购标题栏
            itemBinding.set(BR.viewModel, R.layout.layout_grain_demand_title).bindExtra(BR.presenter, viewGroupPresenter);
        } else if (item instanceof GrainDemandItemViewModel) {   //收购
            itemBinding.set(BR.viewModel, R.layout.layout_item_grain_demand).bindExtra(BR.presenter, viewGroupPresenter);
        } else if (item instanceof NewsTitleViewModel) {  //新闻资讯标题
            itemBinding.set(BR.viewModel, R.layout.layout_news_title).bindExtra(BR.presenter, viewGroupPresenter);
        } else if (item instanceof NewsItemViewModel) {   //新闻
            if (((NewsItemViewModel) item).imgs.size() >= 3) {    //图片数量大于3
                itemBinding.set(BR.viewModel, R.layout.layout_item_news_multi_img).bindExtra(BR.presenter, viewGroupPresenter);
            } else {
                itemBinding.set(BR.viewModel, R.layout.layout_item_news).bindExtra(BR.presenter, viewGroupPresenter);
            }
        }
    }

    @Override
    public void refreshData(boolean init) {
        super.refreshData(init);
        lastRefreshTime = System.currentTimeMillis();
        otherDataRepository.getBanner(new DefaultObserver<List<Banner>>() {

            @Override
            public void onNext(List<Banner> banners) {
                bannerItems.clear();
                if (banners != null && !banners.isEmpty()) {
                    for (Banner item : banners) {
                        BannerItemViewModel itemViewModel = new BannerItemViewModel();
                        itemViewModel.setPic(DataSetting.getPicUrl(item.getPicName()));
                        itemViewModel.setData(item);
                        bannerItems.add(itemViewModel);
                    }
                }
                bannerViewModel.setItems(bannerItems);
            }

            @Override
            public void onError(MyException e) {
                showToast(e.getMessage());
            }

        }, init);

        otherDataRepository.getHomeData(new DefaultObserver<HomeData>() {

            @Override
            public void onNext(HomeData homeData) {
                setData(homeData);
            }

            @Override
            public void onError(MyException e) {
                setError(e.getMessage());
            }
        }, init);
    }

    @SuppressWarnings("unchecked")
    private void setData(HomeData homeData) {

        if (homeData.getNotices() != null && !homeData.getNotices().isEmpty()) {
            noticeItemViewModel.notices.clear();
            noticeItemViewModel.notices.addAll(homeData.getNotices());
        }

        if (homeData.getGoods() != null && !homeData.getGoods().isEmpty()) {
            hotSellViewModel.setGoods1(homeData.getGoods().get(0));
            if (homeData.getGoods().size() >= 2) {
                hotSellViewModel.setGoods2(homeData.getGoods().get(1));
            }
            if (homeData.getGoods().size() >= 3) {
                hotSellViewModel.setGoods3(homeData.getGoods().get(2));
            }
        }
        data.removeAll(list);
        list.clear();
        if (homeData.getAdvertising() != null && !homeData.getAdvertising().isEmpty()) {
            Banner adItem = homeData.getAdvertising().get(0);
            list.add(new AdViewModel(adItem.getPicName(), adItem.getTypeId(), adItem.getTargetId(), adItem.getUrl()));
        }

        if (homeData.getGrainDemands() != null && !homeData.getGrainDemands().isEmpty()) {
            list.add(new GrainDemandTitleViewModel());
            for (GrainDemand item : homeData.getGrainDemands()) {
                list.add(new GrainDemandItemViewModel(item));
            }
        }

        if (homeData.getAdvertising() != null && homeData.getAdvertising().size() >= 2) {
            Banner adItem = homeData.getAdvertising().get(1);
            list.add(new AdViewModel(adItem.getPicName(), adItem.getTypeId(), adItem.getTargetId(), adItem.getUrl()));
        }

        if (homeData.getNews() != null && !homeData.getNews().isEmpty()) {
            list.add(new NewsTitleViewModel());

            for (News item : homeData.getNews()) {
                list.add(new NewsItemViewModel(item));
            }
        }
        data.addAll(list);
        commListViewModel.showSuccess();
    }

    @Override
    public void onResume() {
        super.onResume();
        bannerViewModel.setBannerStart(true);

        if (System.currentTimeMillis() - lastRefreshTime >= REFRESH_TIME_INTERVAL) {
            refreshData(false);
        }

        viewModel.msgCount.set(userData.getTotalUnReadMsgCount());
    }

    @Override
    public void onPause() {
        super.onPause();
        bannerViewModel.setBannerStart(false);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        bannerViewModel.setBannerStart(!hidden);
        if (!hidden) {
            viewModel.msgCount.set(userData.getTotalUnReadMsgCount());
            if (System.currentTimeMillis() - lastRefreshTime >= REFRESH_TIME_INTERVAL) {
                refreshData(false);
            }
        }
    }


    //banner的点击事件
    private OnBannerListener bannerListener = new OnBannerListener() {
        @Override
        public void OnBannerClick(int position) {
            BannerItemViewModel itemViewModel = bannerViewModel.items.get(position);
            if (itemViewModel == null || itemViewModel.getData() == null) {
                return;
            }
            if (itemViewModel.getData() instanceof Banner) {
                Banner banner = (Banner) itemViewModel.getData();
                if (banner.getTypeId() == 1 && !TextUtils.isEmpty(banner.getUrl())) {   //网页
                    WebViewActivity.start(getActivity(), banner.getUrl());
                } else if (banner.getTypeId() == 2 && !TextUtils.isEmpty(banner.getTargetId())) { //商品
                    GoodsDetailActivity.start(getActivity(), banner.getTargetId());
                } else if (banner.getTypeId() == 3 && !TextUtils.isEmpty(banner.getTargetId())) { //粮食需求
                    DemandDetailActivity.start(getActivity(), banner.getTargetId());
                }
            }
        }
    };

    //公告的点击事件
    private VScrollTextView.OnItemClickListener onNoticesItemClickListener = new VScrollTextView.OnItemClickListener() {
        @Override
        public void onItemClick(int position, Object item) {
            if (getActivity() == null) {
                showToast(R.string.error_activity_is_null);
                return;
            }
            NoticeActivity.start(getActivity());
        }
    };

    @Override
    protected void onListClick(View view) {
        if (getActivity() == null) {
            showToast(R.string.error_activity_is_null);
            return;
        }
        super.onListClick(view);
        switch (view.getId()) {
            case R.id.tv_cooperative:   //合作社
                break;
            case R.id.tv_to_loan:   //我要贷款
                break;
            case R.id.tv_to_buy:    //我要买
                GoodsListActivity.start2Goods(getActivity());
                break;
            case R.id.tv_to_sell:   //我要卖
                break;
            case R.id.tv_serve:   //科技服务
                break;
            case R.id.tv_machinery: //二手农机具
                break;
            case R.id.iv_notice:    //公告
                NoticeActivity.start(getActivity());
                break;
            case R.id.ly_goods1://热卖第1个商品
                GoodsDetailActivity.start(getActivity(), hotSellViewModel.goods1Id);
                break;
            case R.id.ly_goods2://热卖第2个商品
                GoodsDetailActivity.start(getActivity(), hotSellViewModel.goods2Id);
                break;
            case R.id.ly_goods3://热卖第3个商品
                GoodsDetailActivity.start(getActivity(), hotSellViewModel.goods3Id);
                break;
            case R.id.tv_demand_more:  //最优收购-更多
                DemandListActivity.start(getActivity());
                break;
            case R.id.tv_news_more: //新闻资讯-更多
                NewsListActivity.start(getActivity());
                break;
        }
    }


    @Override
    protected void onListItemClick(View view, BaseViewModel viewModel) {
        super.onListItemClick(view, viewModel);
        if (viewModel instanceof AdViewModel) {   // 广告
            if (((AdViewModel) viewModel).action == 1 && !TextUtils.isEmpty(((AdViewModel) viewModel).url)) {   //网页
                WebViewActivity.start(getActivity(), ((AdViewModel) viewModel).url);
            } else if (((AdViewModel) viewModel).action == 2 && !TextUtils.isEmpty(((AdViewModel) viewModel).id)) { //商品
                GoodsDetailActivity.start(getActivity(), ((AdViewModel) viewModel).id);
            } else if (((AdViewModel) viewModel).action == 3 && !TextUtils.isEmpty(((AdViewModel) viewModel).id)) { //粮食需求
                DemandDetailActivity.start(getActivity(), ((AdViewModel) viewModel).id);
            }

        } else if (viewModel instanceof NewsItemViewModel) {   //新闻
            WebViewActivity.start(getActivity(), ((NewsItemViewModel) viewModel).url, ((NewsItemViewModel) viewModel).title.get());
        } else if (viewModel instanceof GrainDemandItemViewModel) {
            DemandDetailActivity.start(getActivity(), ((GrainDemandItemViewModel) viewModel).id);
        }
    }

}
